<?php
$loader->requireOnce('includes/LabQueue/LabQueueModel.class.php');
$loader->requireOnce('includes/LabAssignment/LabAssignmentProcessor.class.php');

/**
 * Processor for lab queue
 * @package modules.dept_laboratory.includes
 * @author viethd
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class LabQueueProcessor {
	private $logger ;
	private $controller;
	function __construct($controller) {
		$this->logger = LoggerManager::getLogger('module.dept_laboratory.includes.LabQueue.LabQueueProcessor');
		$this->controller = $controller;

	}

	/**
	 * Render labqueue by patienttype filter.
	 * @param $enumPatientType
	 * @return html array('waiting'=>'','inprocess'=>'')
	 */
	public function renderQueue($enumPatientType) {
		$result = array('waiting'=>'','inprocess'=>'');
		$labQueueModel = new LabQueueModel($enumPatientType);
		$labQueueModel->buildModel();
		$result['waiting'] = $this->renderWaitingQueue($labQueueModel);
		$result['inprocess'] = $this->renderInProcessQueue($labQueueModel);
		return $result;
	}

	private function renderWaitingQueue($labQueueModel) {
		$labWaitingItems = $labQueueModel->getQueueItems(EnumerationConstant::LAB_ASSIGNMENT_TICKET_WAITING);
		$count = 1;
		$html = '';

		foreach ($labWaitingItems as $item) {
			$patient = Celini::newORDO('Patient', $item->getPatientId());
			$html .= '<tr>';
			$html .= "<td>" . $count++ . "</td";
			$html .= '<td><a href="javascript:startProcessingQueueItem(\'' . $item->getLabAssignmentTicketId()  . '\');">' . $item->getPatientName() . '</a></td>';
			$html .= '<td>' . $patient->get('patient_code') . '</td>';
			$labTicketItem = '';
			foreach ($item->getLabTicketItems() as $ltItem) {
				$labTicketItem .= $ltItem->getName() . "<br>";
			}
			$html .= '<td>' . $labTicketItem . '</td>';
			$html .= '<td>' . L10nHelper::renderDateTime($item->getStartWaiting(), 'short', 'datetime') . '</td>';
			$html .= '<td>' . $item->getTreatmentDepartmentName() . '</td>';
			$html .= '</tr>';
		}
		$total = '<table cellspacing="0" cellpadding="0" style="width: 100%;">';
        $total .= '<tr class="last"><td>'.L10nHelper::_("Total: <span class='impression'>%s<span>",--$count).'</td></tr>';
        $total .= '</table>';
		if ($html == '') {
			$html = '<tr class="last"><td colspan="6">' . L10nHelper::_('There is no result') . '</td></tr>';
		}
        return array('body' => $html, 'total_table' => $total); 
	}

	private function renderInProcessQueue($labQueueModel) {
		$labProcessingItems = $labQueueModel->getQueueItems(EnumerationConstant::LAB_ASSIGNMENT_TICKET_INPROGRESS);
		$count = 1;
		$html = '';
		foreach ($labProcessingItems as $item) {
			$patient = Celini::newORDO('Patient', $item->getPatientId());
			$html .= '<tr>';
			$html .= "<td>" . $count++ . "</td";
			$html .= '<td><a href="javascript:viewInputLabResultPage(\'' . $item->getLabAssignmentTicketId()  . '\',\'\');">' . $item->getPatientName() . '</a></td>';
			$html .= '<td>' . $patient->get('patient_code') . '</td>';
			$labTicketItem = '';
			foreach ($item->getLabTicketItems() as $ltItem) {

				if ($ltItem->isDone()) {
					$labTicketItem .= '<input type="checkbox" disabled="disabled" checked="checked"></input>';
				} else {
					$labTicketItem .= '<input type="checkbox" disabled="disabled"></input>';
				}
				$labTicketItem .= '<a href="javascript:viewInputLabResultPage(\''
				. $item->getLabAssignmentTicketId()
				. '\',\'' . $ltItem->getLabTicketId() .'\');">';
				$labTicketItem .= $ltItem->getName() ;
				$labTicketItem .= '</a>';
				$labTicketItem .= '<br>';
			}
			$html .= '<td>' . $labTicketItem . '</td>';
			$html .= '<td>' . L10nHelper::renderDateTime($item->getStartProcess(), 'short', 'datetime') . '</td>';
			$html .= '<td>' . $item->getTreatmentDepartmentName() . '</td>';
			$html .= '<td>';
			$html .= '<a href="javascript:cancelProcessingQueueItem(\'' . $item->getPatientName()
			. "','"
			. $item->getLabAssignmentTicketId()  . '\');">' . L10nHelper::_("Lab_Call_Cancel") .'</a>';
			$html .= '&nbsp;';
			$html .= '<a href="javascript:finishProcessingQueueItem(\'' . $item->getPatientName()
			. "','"
			. $item->getLabAssignmentTicketId()  . '\');">' . L10nHelper::_("Lab_Finish") .'</a>';
			$html .= '</td>';

			$html .= '</tr>';
		}
		if ($html == '') {
			$html = '<tr class="last"><td colspan="7">' . L10nHelper::_('There is no result') . '</td></tr>';
		}
		$total = '<table cellspacing="0" cellpadding="0" style="width: 100%;">';
        $total .= '<tr class="last"><td>'.L10nHelper::_("Total: <span class='impression'>%s<span>",--$count).'</td></tr>';
        $total .= '</table>';
        return array('body' => $html, 'total_table' => $total);		
	}

	/**
	 * Add patient into lab queue
	 * @param $labAssignmentTicketId
	 * @return unknown_type
	 */
	public function addPatient($labAssignmentTicketId) {
		$labQueueObj = Celini::newOrdo('LabQueue');
		$isExist = $labQueueObj->isItemExist($labAssignmentTicketId);
		if ($isExist) {
			//not start a lab assignment ticket already added into lab queue
			$this->logger->warn("Not add lab assignment[" . $labAssignmentTicketId
			. "]  into queue because it was added");
			return 0;
		}
		$labQueueInfo = array(
         'lab_assignment_ticket_id' => $labAssignmentTicketId,
		 'start_waiting' => date("Y-m-d H:i:s")
		);
		$labQueueObj->setData($labQueueInfo);
		$labQueueObj->persist();
		return $labQueueObj->get_id();
	}


	public function startProcessQueueItem($labAssignmentTicketId) {
		$labAssignmentProcessor = new LabAssignmentProcessor(null);
		$labAssignmentProcessor->changeLabAssignmentStatus($labAssignmentTicketId,
		EnumerationConstant::LAB_ASSIGNMENT_TICKET_INPROGRESS);
		$labQueue = Celini::newOrdo('LabQueue');
		$labQueue->updateStartProcess($labAssignmentTicketId);
		//call labassignment processor
		$labAssignmentProcessor = new LabAssignmentProcessor(null);
		$labAssignmentProcessor->doWhileAssignmentProcessing($labAssignmentTicketId);


	}
	public function cancelProcessingQueueItem($labAssignmentTicketId) {
		if ($this->canCancelAssignment($labAssignmentTicketId)) {
			$labAssignmentProcessor = new LabAssignmentProcessor(null);
			$labAssignmentProcessor->changeLabAssignmentStatus($labAssignmentTicketId,
			EnumerationConstant::LAB_ASSIGNMENT_TICKET_WAITING);
			$labAssignmentProcessor = new LabAssignmentProcessor(null);
			$labAssignmentProcessor->doAfterAssignmentCanceled($labAssignmentTicketId);
		} else {
			throw new LabException("Could not cancel the lab assignment["
			. $labAssignmentTicketId
			."] because it status is [done] or was inputed result.",
			LabErrorCode::QUEUE_COULD_NOT_CANCEL);
		}

	}

	public function finishProcessingQueueItem($labAssignmentTicketId) {
		//change assignment status
		$labAssignmentProcessor = new LabAssignmentProcessor(null);
		$labAssignmentProcessor->changeLabAssignmentStatus($labAssignmentTicketId,
		EnumerationConstant::LAB_ASSIGNMENT_TICKET_DONE);
		//remove from queue
		$this->removePatient($labAssignmentTicketId);
		//call labassignment processor to finish this assignment
		$labAssignmentProcessor = new LabAssignmentProcessor(null);
		$labAssignmentProcessor->finishAssignment($labAssignmentTicketId);


	}

	public function preFinishProcessingQueueItem($labAssignmentTicketId) {
		//change assignment status
		$labTicketObj = Celini::newOrdo('LabTicket');
		$listOflabTicket = $labTicketObj->listLabTickets($labAssignmentTicketId);
		$result = array();
		foreach ($listOflabTicket as $item) {
			if ($item['is_done'] == 0) {
			     $result[]= $item['name'] ; 
			}			
		}				
		return implode(',', $result);
	}
	/**
	 * @param $labAssignmentTicketId
	 * @return unknown_type
	 */
	private function removePatient($labAssignmentTicketId) {
		$labQueueObj = Celini::newOrdo('LabQueue');
		$labQueueObj->deleteItem($labAssignmentTicketId);
	}
	private function canCancelAssignment($labAssignmentTicketId) {
		$labAssignmentTicketObj = Celini::newOrdo('LabAssignmentTicket');
		$labAssignmentTicketObj->setup($labAssignmentTicketId);
		$status = $labAssignmentTicketObj->get('enum_status');
		//false if this assignment already done.
		if ($status == Utils::getEnumKey(EnumerationConstant::LAB_ASSIGNMENT_TICKET_STATUS,
		EnumerationConstant::LAB_ASSIGNMENT_TICKET_DONE)) {
			return false;
		}
		//false if this assignment already input result.
		$labTicketObj = Celini::newOrdo('LabTicket');
		$listOflabTicket = $labTicketObj->listLabTickets($labAssignmentTicketId);
		foreach ($listOflabTicket as $item) {
			if ($item['is_done'] != 0) {
				return false;
			}
		}

		return true;
			
	}

}
?>